package com.oceansoft.mobile.econsole.modules.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.survey.entity.Answer;
import com.oceansoft.mobile.econsole.survey.entity.QuestionExt;
import com.oceansoft.mobile.econsole.survey.entity.Survey;
import com.oceansoft.mobile.econsole.survey.service.ISurveyService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * Created by liujie on 2016/9/6.
 */
@Controller
@RequestMapping("api/survey")
public class ApiSurveyController {
    @Resource
    ISurveyService surveyService;

    @RequestMapping(value = "index/{surveyid}", method = GET)
    public String getIndex(@PathVariable("surveyid") String surveyId, Model model) {
        Survey survey = surveyService.getSurveyById(Integer.parseInt(surveyId));
        List<QuestionExt> questionList = surveyService.getQuestionsBySurvey(survey);
        int count = questionList.size();
        model.addAttribute("survey",survey);
        model.addAttribute("questionList", JSONArray.toJSONString(questionList));
        model.addAttribute("count",count);
        return "survey/do-survey";
    }

    @ResponseBody
    @RequestMapping(value = "submit", method = POST)
    public Result editQuestion(HttpServletRequest request) {
        int count = Integer.parseInt(request.getParameter("count"));
        List<Answer> answers = new ArrayList<Answer>();
        for(int i=0;i<count;i++){
            Answer answer = new Answer();
            answer.setQuestionid(Integer.parseInt(request.getParameter("question"+i)));
            answer.setOptionid(Integer.parseInt(request.getParameter("option"+i)));
            answers.add(answer);
        }
        try {
            Result r = surveyService.saveAnswers(answers);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "提交参数有误");
        }
    }
}
